/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package xmldatabase;

import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 *
 * @author betty
 */
public class Newxml {

    public void createXML(Newsinfo newsinfo) throws Exception {
        //1.创建document对象，代表整个xml文档
        Document document = DocumentHelper.createDocument();
        //2.创建根节点
        Element news = document.addElement("news");
        //3.向rss节点中添加version，自动生成默认编码模式（UTF-8）
        //4.生成子节点及节点内容
        Element information = news.addElement("information");
        Element id = information.addElement("id");
        Element title = information.addElement("title");
        Element reporter = information.addElement("reporter");
        Element editer = information.addElement("editer");
        Element abstr = information.addElement("abstract");
        Element state = information.addElement("state");
        Element time = information.addElement("time");

        Element year = time.addElement("year");
        Element month = time.addElement("month");
        Element day = time.addElement("day");
        Element hour = time.addElement("hour");
        Element minute = time.addElement("minute");
        Element second = time.addElement("second");

        Element category = information.addElement("category");
        Element body = news.addElement("body");
        Element text = body.addElement("text");

        //title.setText("中国最新新闻");
        id.setText(Integer.toString(newsinfo.getId()));
        title.setText(newsinfo.getTitle());
        reporter.setText(newsinfo.getReporter());
        abstr.setText(newsinfo.getAbs());
        state.setText(newsinfo.getState());

        year.setText(Integer.toString(newsinfo.getYear()));
        month.setText(Integer.toString(newsinfo.getMonth()));
        day.setText(Integer.toString(newsinfo.getDay()));
        hour.setText(Integer.toString(newsinfo.getHour()));
        minute.setText(Integer.toString(newsinfo.getMin()));
        second.setText(Integer.toString(newsinfo.getSec()));
        category.setText(newsinfo.getCate());
        text.setText(newsinfo.getText());
        editer.setText(newsinfo.getEditer());

        //5.设置生成xml的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //生成不一样的编码
        format.setEncoding("UTF-8");
        //6.生成xml文件
        File file = new File("C:\\Users\\betty\\Desktop\\" + newsinfo.getId());
        XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
        //设置是否转义，默认设置是true,代表转义
        writer.setEscapeText(false);
        writer.write(document);
        writer.close();
    }
}
